package com.lanyeo.liver.util

import android.util.Log
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.util.zip.ZipInputStream

object Zip {
    private const val TAG = "ZIP"
    fun decompress(zipStream: ZipInputStream, outPath: String): Boolean {
        val outDir = File(outPath)
        if (outDir.exists()) {
            if (!outDir.isDirectory) {
                Log.e(TAG, "out is file! $outPath")
                return false
            }
        } else {
            outDir.mkdirs()
        }
        var zipEntry = zipStream.nextEntry
        while (zipEntry != null) {
            var filename = outPath
            if (!filename.endsWith( File.separatorChar)) {
                filename += File.separatorChar
            }
            filename += zipEntry.name
            val zipTempFile = File(filename)

            if (zipEntry.name.endsWith(File.separatorChar)) {
                zipTempFile.mkdirs()
            } else {
                if (!zipTempFile.parentFile.exists()) {
                    zipTempFile.parentFile.mkdirs()
                }
                val fileOutputStream = FileOutputStream(zipTempFile)
                val bufferedOutputStream = BufferedOutputStream(fileOutputStream)
                var readSize = 0
                val buffer = ByteArray(1024 * 10)
                while(true) {
                    readSize = zipStream.read(buffer)
                    if (readSize == -1) break else {
                        bufferedOutputStream.write(buffer, 0, readSize)
                    }
                }
                bufferedOutputStream.flush()
                bufferedOutputStream.close()
                fileOutputStream.close()
            }
            zipStream.closeEntry()
            zipEntry = zipStream.nextEntry
        }
        return true
    }
}